#include <SimpleDHT.h>
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <ESP8266WiFi.h>

// WiFi settings
const char* ssid     = "wifiname";          //WiFi名
const char* password = "123456";    //WiFi密码

// OLED 128x64 接法
// VCC  3.3v
// GND  GND
//SCK D1  5
//SDA D2  4
LiquidCrystal_I2C lcd(0x27,16,2);  // 设置液晶地址 0x27  设置一行显示的字符 16个 2 行显示
// for DHT11, 
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = D4;
SimpleDHT11 dht11(pinDHT11);

const char* host = "xx.xxx.com"; //推送的域名
const int httpsPort = 80;  // 需要访问的端口
String url = "/api/index/up";   // 需要访问的地址

void setup() {
  Serial.begin(115200);
   lcd.backlight();   //打开背光
   delay(10);
    Serial.print("Connecting to WIFI");
  Serial.println(ssid);
  //启动wifi连接，ssid为wifi名字，password为密码
  WiFi.begin(ssid, password);
  //轮询等待wifi连接完成 即 wifi.status() 状态为 WL_CONNECTED（表示已经连接上了）
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("读取温度湿度中...");
  
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("读取成功: ");
  Serial.print((int)temperature); Serial.print(" *C, "); 
  Serial.print((int)humidity); Serial.println(" H");
    // 可以输出到OLED 0.96  IIC接口 
  lcd.init();                      //初始化
  lcd.print(temperature);  //输出内容
  lcd.print(" *C, ");  //输出内容
  lcd.print(humidity);  //输出内容
  lcd.print(" *H, ");  //输出内容
  // DHT11 sampling rate is 1HZ.

  //连接网站
  WiFiClient client;  
   /**
   * 测试是否正常连接
   */
  if (!client.connect(host, httpsPort)) {  
    Serial.println("connection failed");  
    return;  
  }
  //下面为推送数据
  int temp= temperature;
  int hum= humidity;
  String pUrl=url+"?t="+temp+"&h="+hum;
  String postRequest =(String)("GET ") + pUrl + " HTTP/1.1\r\n" +  
    "Content-Type: text/html;charset=utf-8\r\n" +  
    "Host: " + host + "\r\n" + 
    "User-Agent: BuildFailureDetectorESP8266\r\n" +
    "Connection: Keep Alive\r\n\r\n";  
  Serial.println(postRequest);
  client.print(postRequest);  // 发送HTTP请求

  /**
   * 展示返回的所有信息
   */
  String line = client.readStringUntil('\n');
  while(line.length() != 0){
    Serial.println(line);
    line = client.readStringUntil('\n');
  }
  Serial.println(line);
  client.stop();

// 每隔60秒检测并发送
  delay(60000);
}
